// 1. React核心库
import React, { useState, useEffect, useCallback } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Card,
  Row,
  Col,
  Statistic,
  Button,
  Space,
  Typography,
  Avatar,
  List,
  Tag,
  Empty,
} from 'antd';

// 3. 图标库
import {
  UserOutlined,
  TeamOutlined,
  ClockCircleOutlined,
  RiseOutlined,
  EyeOutlined,
  PlusOutlined,
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 工具库
import { history, useModel } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserProfile } from '@/services/generated/src';

// 解构常用子组件
const { Title, Text } = Typography;

interface DashboardStats {
  totalUsers: number;
  activeUsers: number;
  adminUsers: number;
  recentUsers: any[];
}

const Home: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    activeUsers: 0,
    adminUsers: 0,
    recentUsers: [],
  });
  const [statsLoading, setStatsLoading] = useState(false);

  // 获取仪表板统计数据
  const fetchStats = useCallback(async () => {
    try {
      setStatsLoading(true);
      await autoLoginInDev();

      // 获取用户列表统计
      const response = await apiClients.users.usersList({
        page: 1,
        pageSize: 10,
      });

      console.log('🚀 首页统计API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const responseData = (response as any).data || response;
      const users = responseData?.items || [];
      const total = responseData?.total || 0;

      const activeCount = users.filter((user: any) => user.is_active).length;
      const adminCount = users.filter((user: any) => user.is_staff).length;

      setStats({
        totalUsers: total,
        activeUsers: activeCount,
        adminUsers: adminCount,
        recentUsers: users.slice(0, 5),
      });
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setStatsLoading(false);
    }
  }, []);

  // 初始化数据获取
  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  const currentUser = initialState?.currentUser;

  return (
    <PageContainer
      header={{
        title: '欢迎回来',
        subTitle: currentUser ? `${currentUser.full_name || currentUser.username}，今天也要加油哦！` : '用户管理系统',
        breadcrumb: {
          items: [
            { title: '首页' },
          ],
        },
      }}
    >
      {/* 欢迎卡片 */}
      <Card style={{ marginBottom: 24 }}>
        <Row align="middle">
          <Col flex="auto">
            <Space size="large">
              <Avatar size={64} icon={<UserOutlined />} />
              <div>
                <Title level={3} style={{ margin: 0 }}>
                  {currentUser?.full_name || currentUser?.username || '访客'}
                </Title>
                <Text type="secondary">
                  {currentUser?.is_staff ? '管理员' : '普通用户'} • 
                  最后登录: {currentUser?.last_login ? new Date(currentUser.last_login).toLocaleString() : '首次登录'}
                </Text>
              </div>
            </Space>
          </Col>
          <Col>
            <Space>
              <Button 
                type="primary" 
                icon={<EyeOutlined />}
                onClick={() => history.push('/users/list')}
              >
                查看用户
              </Button>
              <Button 
                icon={<PlusOutlined />}
                onClick={() => history.push('/users/create')}
              >
                创建用户
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计卡片 */}
      <Row gutter={24} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={stats.totalUsers}
              prefix={<TeamOutlined />}
              valueStyle={{ color: '#1890ff' }}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={stats.activeUsers}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#52c41a' }}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="管理员"
              value={stats.adminUsers}
              prefix={<RiseOutlined />}
              valueStyle={{ color: '#faad14' }}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日新增"
              value={0}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#722ed1' }}
              loading={statsLoading}
            />
          </Card>
        </Col>
      </Row>

      {/* 最近用户 */}
      <Row gutter={24}>
        <Col span={12}>
          <Card 
            title="最近注册用户" 
            extra={
              <Button 
                type="link" 
                onClick={() => history.push('/users/list')}
              >
                查看全部
              </Button>
            }
          >
            {stats.recentUsers.length > 0 ? (
              <List
                dataSource={stats.recentUsers}
                renderItem={(user: any) => (
                  <List.Item
                    actions={[
                      <Button 
                        type="link" 
                        size="small"
                        onClick={() => history.push(`/users/detail/${user.id}`)}
                      >
                        查看
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<UserOutlined />} />}
                      title={
                        <Space>
                          {user.full_name || user.username}
                          <Tag color={user.is_active ? 'green' : 'red'}>
                            {user.is_active ? '激活' : '禁用'}
                          </Tag>
                          {user.is_staff && <Tag color="orange">管理员</Tag>}
                        </Space>
                      }
                      description={
                        <Space direction="vertical" size={0}>
                          <Text type="secondary">{user.email}</Text>
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            注册时间: {new Date(user.date_joined).toLocaleDateString()}
                          </Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无用户数据" />
            )}
          </Card>
        </Col>
        
        <Col span={12}>
          <Card title="快速操作">
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <Button 
                type="primary" 
                block 
                size="large"
                icon={<PlusOutlined />}
                onClick={() => history.push('/users/create')}
              >
                创建新用户
              </Button>
              <Button 
                block 
                size="large"
                icon={<TeamOutlined />}
                onClick={() => history.push('/users/list')}
              >
                管理用户列表
              </Button>
              <Button 
                block 
                size="large"
                icon={<UserOutlined />}
                onClick={() => history.push('/auth/me')}
              >
                个人资料设置
              </Button>
            </Space>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default Home;
